
package ivan.cheng.activitys;

import ivan.cheng.Const;
import ivan.cheng.R;
import ivan.cheng.adapter.PackageListAdapters.PackageListAdapter;
import ivan.cheng.utils.LogUtil;
import ivan.cheng.views.MyListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class PermissionByNumberActivity extends UIActivity {
    
    private PackageListAdapter adapter;
    private PackageManager mPackageManager;
    private BroadcastReceiver loadFinish = new LoadFinishReceiver();
    private List<PackageInfo> packageList = null;// = new ArrayList<PackageInfo>();
    private MyListView listView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.list_detail);
        mTitle = (TextView)findViewById(R.id.custom_title_txt);
		mTitle.setText(R.string.tab_title_number);
        listView = (MyListView) this.findViewById(R.id.listbody);
        mPackageManager = this.getApplicationContext().getPackageManager();
        IntentFilter filter = new IntentFilter(Const.ACTION_PERMISSION_LOADFINISH);
        this.registerReceiver(loadFinish, filter);
        
        //ComponentName cn = new ComponentName(pkg, cls)
       // mPackageManager.setComponentEnabledSetting(componentName, newState, flags)
        listView.setOnItemClickListener(new OnItemClickListener() 
        {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) 
			{//试试看能否禁止开机启动
				showInstalledAppDetails(packageList.get(position).packageName);
			}
		});
        //添加列表的头部信息，这个要放在setadapter之前
//        View view = LayoutInflater.from(PermissionByNumberActivity.this).inflate(R.layout.explain_head_item, null);
//        TextView tv = (TextView)view.findViewById(R.id.tv_explain);
//        tv.setText(Html.fromHtml(GetPermissionExplain(permissionName)));
//        getListView().addHeaderView(view,null,false);
        //获取数据刷新列表
        refresh();
    }

    /**
     * 显示系统设置应用程序详细界面
     * 
     * @param packageName
     */
    public void showInstalledAppDetails(String packageName) {  
        Intent intent = new Intent();  
        final int apiLevel = Build.VERSION.SDK_INT;  
        if (apiLevel >= 9) { // 2.3（ApiLevel 9）以上，使用SDK提供的接口  
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");  
            Uri uri = Uri.fromParts("package", packageName, null);  
            intent.setData(uri);  
        } else { // 2.3以下，使用非公开的接口
            // 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。  
            final String appPkgName = (apiLevel == 8 ? "pkg"  
                    : "com.android.settings.ApplicationPkgName");  
            intent.setAction(Intent.ACTION_VIEW);  
            intent.setClassName("com.android.settings",  
                    "com.android.settings.InstalledAppDetails");  
            intent.putExtra(appPkgName, packageName);  
        }  
        startActivity(intent);  
    }  
    
    private MyListView getListView() {
        return listView;
    }
    
    public void refresh() {
        setProgressBarIndeterminateVisibility(true);
        if(null != packageList)
        	packageList.clear();
        packageList = mPackageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS);
        Iterator<PackageInfo> it = packageList.iterator();
    	while(it.hasNext())
    	{
    		PackageInfo pi = it.next();
    		if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0
					|| (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) > 0)
			{
				it.remove();
			}
//    		if(pi.applicationInfo.publicSourceDir.contains("/system/app/")||
//    				pi.applicationInfo.publicSourceDir.contains("/framework/system/"))
//    		{
//    			it.remove();
//    		}
    	}
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() 
			{
				
				Collections.sort(packageList, new Comparator<PackageInfo>() 
						{
							
							@Override
							public int compare(PackageInfo lhs, PackageInfo rhs) 
							{

								int lLenth = 0,rLenth = 0;
								if(null != lhs.requestedPermissions)
								{
									lLenth = lhs.requestedPermissions.length;
								}
								if(null != rhs.requestedPermissions)
								{	
									rLenth = rhs.requestedPermissions.length;
								}
								if(lLenth == rLenth)
									return 0;
								return lLenth > rLenth?-1:1;
							}

				});
				Intent in = new Intent(Const.ACTION_PERMISSION_LOADFINISH);
				PermissionByNumberActivity.this.sendBroadcast(in);
			}

		});
		t.start();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //refresh();
    }

	private String GetPermissionExplain(String sPermission) 
	{
		try {
			PermissionInfo tmpPermInfo = mPackageManager.getPermissionInfo(sPermission, 0);// 通过permName得到该权限的详细信息
			PermissionGroupInfo pgi = mPackageManager.getPermissionGroupInfo(
					tmpPermInfo.group, 0);// 权限分为不同的群组，通过权限名，我们得到该权限属于什么类型的权限。
			
			StringBuilder sb = new StringBuilder();
			sb/*.append("-" + sPermission + "\n")*/
					.append("<b><font size=\"5\" color=\"0x3acbff\">权限类别</font></b>")
					.append("-" + pgi.loadLabel(mPackageManager).toString() + "<br>")
					.append("<b><font size=\"5\" color=\"0x3acbff\">权限描述</font></b>")
					.append("-" + tmpPermInfo.loadLabel(mPackageManager).toString() + "<br>")
					.append("<b><font size=\"5\" color=\"0x3acbff\">权限详情</font></b>")
					.append("-" + tmpPermInfo.loadDescription(mPackageManager).toString()
							);
			return sb.toString();

		} 
		catch (NameNotFoundException e) 
		{
			LogUtil.w("Could'nt retrieve permissions for package");
		}
		return "";
	}

    private class LoadFinishReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context ctx, Intent intent) {
            PermissionByNumberActivity.this.setProgressBarIndeterminateVisibility(false);
            adapter = new PackageListAdapter(PermissionByNumberActivity.this, packageList);
            
            PermissionByNumberActivity.this.getListView().setAdapter(adapter);
        }
    }


	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(loadFinish);
	}

	@Override
	public void PackageAdded(String packageName) 
	{
//		for(String name:packageNameLst)
//		{
//			if(name.equalsIgnoreCase(packageName))
//			{
//				packageNameLst.remove(name);
				refresh();
//				break;
//			}
//		}
	}

	@Override
	public void PackageRemoved(String packageName) 
	{
//		for(String name:packageNameLst)
//		{
//			if(name.equalsIgnoreCase(packageName))
//			{
//				packageNameLst.remove(name);
				refresh();
//				break;
//			}
//		}
	}
    
}
